package com.anc.web.filter;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {
    public final static String MDC_TRACE_ID = "traceId";
    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 使用雪花算法生成一个请求Id
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String traceId = Long.toString(IdWorker.getId());

//        MDC.put(MDC_TRACE_ID, traceId);
//        ThreadLocalUtils.setTraceId(traceId);
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setHeader(MDC_TRACE_ID, traceId);
        filterChain.doFilter(request, servletResponse);

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
        MDC.clear();
    }
}
